programming4us
           
 
 
Programming

Programming Excel with VBA and .NET : Tasks in Visual Basic - Work with Text

- Free product key for windows 10
- Free Product Key for Microsoft office 365
- Malwarebytes Premium 3.7.1 Serial Keys (LifeTime) 2019
8/11/2011 5:13:28 PM
Working with text is probably just as common as working with numbers in most programs. Visual Basic refers to text data as strings and it provides a set of string operators and functions just as it does for math. Since strings and numbers are very different types of data, the nature of operators and functions are very different, as shown by Tables 1 and 2.
Table 1. Visual Basic string operators
& (join)Like (compare)= (assign)

Table 2. Visual Basic string functions
TaskFunctionUse to
CompareOption CompareChange the string comparison rules
 InstrFind one string inside of another
 StrCompCompare one string to another
ConvertAscConvert a character to its numeric ANSI value
 ChrConvert a numeric ANSI value to a character
 FormatConvert a number or a date to a string using a specific format
 LCaseMake a string lowercase
 UCaseMake a string uppercase
 StrConvChange the capitalization, locale, or encoding of a string
 ValGet the numeric value of a string
ArraysSplitConvert a string to a one-dimensional array
 JoinConvert a one-dimensional array to a string
ChangeLeftGet a number of characters from the left side of the string
 LenGet the length of a string
 LTrimRemove spaces from the left side of a string
 LSetCopy one string to another, left-aligning the result
 MidGet a specified number of characters from within as string
 ReplaceSearch and replace words or characters in a string
 RightGet a number of characters from the right side of a string
 RSetCopy one string to another, right-aligning the result
 RTrimRemove spaces from the right side of a string
 TrimRemove spaces from the right and left sides of a string
RepeatSpaceCreate a string containing a number of spaces
 StringCreate a string containing a repeating character

The following sections explain how to use the string functions to perform the major tasks listed in Table 2.

1. Compare Strings

By default, Visual Basic compares strings in a case-sensitive way. That means "Jeff" and "jeff" are not considered the same. You can change that by adding an Option Compare Text statement at the beginning of a module or class, as shown here:

    ' Ignore case when comparing 
strings.
Option Compare Text

Sub CompareStrings( )
' Displays True if Option Compare is Text.
Debug.Print "Jeff" = "jeff"
End Sub

Option Compare applies to all the ways to compare string (=, Like, StrComp) throughout the module or class. You can achieve a similar result on a smaller scale by temporarily converting the strings to upper- or lowercase before comparing them:

    Debug.Print LCase("Jeff") = LCase("jeff")

That approach is actually more common than changing Option Compare since it allows you to use both case-sensitive and case-insensitive comparisons within a class or module.

The Like operator is similar to = in Visual Basic, except it also allows you to match patterns of characters using the comparison characters listed in Table 3.

Table 3. Pattern-matching characters
UseTo match
?Any single character
*Zero or more characters
#Any single digit
[list]Any single character in list
[!list]Any single character not in list

For example, the following function returns True if a passed-in argument is formatted as a Social Security number:

    Function IsSSN(ssn As String) As Boolean
If ssn Like "###-##-####" Then
IsSSN = True
Else
IsSSN = False
End If
End Function

The Instr function returns the location of one string within another string. This is one of the most-used functions in Visual Basic, since it allows you to break up strings and to do all sorts of search-and-replace tasks.

The StrComp function compares two strings for sorting . If the first string sorts before the second string, StrComp returns -1; if they sort the same, it returns 0; and if the first string sorts after the second string, StrComp returns 1. The following example demonstrates how to use StrComp to sort an array:

    Sub SortArray(arr As Variant, _
Optional compare As VbCompareMethod = vbBinaryCompare)
Dim lb As Integer, ub As Integer, i As Integer, str As String
Dim j As Integer
' If argument is not an array, then exit.
If Not IsArray(arr) Then Exit Sub
lb = LBound(arr)
ub = UBound(arr)
' If only one element, then exit.
If lb = ub Then Exit Sub
For i = lb To ub
str = arr(i)
For j = lb To ub
' Swap values if out of order.
If StrComp(str, arr(j), compare) = -1 Then
str = arr(j)
arr(j) = arr(i)
arr(i) = str
End If
Next
Next
End Sub



There are more efficient sorting routines than the one shown here. I chose this one for its simplicity.


The SortArray procedure lets you specify whether or not to ignore the case of characters when sorting. The default is to use vbBinaryCompare for case-sensitive sorting. You can use the SortArray function to create a function that sorts strings:

    Function SortString(str As String, Optional ignorecase = False)
Dim arr As Variant
' Covert the string to an array.
arr = Split(str, " ")
' Sort the array case-sensitive or case-insensitive.
If ignorecase Then
SortArray arr, vbTextCompare
Else
SortArray arr, vbBinaryCompare
End If
' Convert the array back to a string and return it.
SortString = Join(arr, " ")
End Function

To see how these functions work together, step through the following code in the sample worksheet:

    Sub DemoSort( )
Dim str As String, arr As Variant
str = "Q z v w p x f g J l h r y D k i e T s u o n M a c b"
' Show case-sensitive sort.
Debug.Print SortString(str, False)
' Show case-insensitive sort.
Debug.Print SortString(str, True)
End Sub

I have an ulterior motive for showing you these procedures: I'm often asked how you break tasks into procedures and I think this set of procedures illustrates the logical division of tasks very well. SortString and SortArray both make sense as a stand-alone procedure because they might be reused any number of ways elsewhere in the program. Writing effective, reusable procedures is one of the key skills that identify you as an excellent programmer. The best way to learn that skill is by studying good examples and then practicing on your own!

2. Convert Strings

I touched on two very common conversion functions already: LCase and UCase convert a string to lower- or uppercase, usually because you want to ignore case while comparing strings. Your computer can perform these conversions and comparisons because it actually stores strings as numbers using something called ANSI character codes .

The Asc function converts characters to their numeric ANSI character codes; Chr converts those numeric codes back to characters. The following code displays the ANSI character codes in the Immediate window (Figure 3-2):

    Sub ShowAnsiCodes( )
Dim i As Integer, str As String
For i = 0 To 255
str = str & i & ": " & Chr(i) & vbTab
If i Mod 10 = 0 Then
Debug.Print str
str = ""
End If
Next
End Sub

Not all character codes have an appearance. Chr(0), Chr(9), Chr(10), and Chr(13) represent the null, tab, line-feed, and carriage-return characters respectively.


Looking at Figure 1, you can see that you can convert individual characters from upper- to lowercase by adding 32 or from lower- to uppercase by subtracting 32. UCase and LCase just make those conversions easier.

The StrConv function is related to UCase and LCase. It can perform the same conversions, plus it can convert the words in a string to use initial capitalization as is used in proper names:

    ' Displays St. Thomas Aquinas
Debug.Print StrConv("st. thomas aquinas", vbProperCase)

StrConv also converts strings to or from other encodings or locales. Those are pretty advanced topics and I'm just going to skip them here.


Figure 1. ANSI character codes

The Format function converts various types of data into strings using predefined or custom formats. The Val function converts strings containing numeric data back into numeric data types. This simple example illustrates how these functions work:

    Sub ShowFormatVal( )
Dim num As Double, str As String
str = Format(Now, "Short Time")
num = Val(str)
' If the time is 4:31 PM, displays: 16:31 16
Debug.Print str, num
End Sub

You might notice that Val doesn't do anything fancy—it just gets the first part of the string that is numeric and returns it as a number. Val can recognize a few special strings as numbers. For instance, it interprets &HFF as the hexadecimal (base 16) number 255 and &o77 as the octal (base 8) number 63. Format is really more interesting, since it provides useful built-in formats as listed in Table 4.

Table 4. The Format function's built-in formats
CategoryNamed formatConverts
NumericGeneral NumberNumber to string without thousands separator. This is the default.
 CurrencyNumber to string using the decimal, separator, and currency characters that are appropriate for the locale. Negative values are enclosed in parentheses.
 FixedNumber to string with at least one digit to the left of the decimal and two digits to the right of the decimal.
 StandardSame as Fixed but includes a thousands separator.
 PercentMultiplies number by 100 and includes at least two digits to the right of the decimal.
 ScientificNumber to string using standard scientific notation.
 Yes/NoZero to No, nonzero to Yes.
 True/FalseZero to False, nonzero to True.
 On/OffZero to Off, nonzero to On.
Date/TimeGeneral DateNumber or date to string using MM/DD/YY HH:MM:SS format. Omits time if number is a whole number.
 Long DateNumber or date to string using your system's long date format.
 Medium DateNumber or date to string using your system's medium date format.
 Short DateNumber or date to string using your system's short date format.
 Long TimeNumber or date to string using your system's long time format. Includes hours, minutes, and seconds.
 Medium TimeNumber or date to string in 12-hour time format. Includes hours, minutes, and AM/PM designator.
 Short TimeNumber or date to string in 24-hour time format. Includes hours and minutes.

If the built-in formats don't give you what you need, you can build your own format strings using the Format function's formatting codes listed in Table 5.

Table 5. The Format function's formatting codes
CategoryCodeUse to
String@Include a character or space if there is no character in this position (creates fill spaces for columns).
 &Include a character (no fill).
 <Force lowercase.
 >Force uppercase.
 !Right-align string (default is left-align).
 \Include characters that otherwise have special meaning in the format string (e.g., use \@ to include the @ character).
 ""literal""Include literal characters in a format string.
NumericNoneInclude number with no special formatting.
 0Include a digit or zero if there is no digit in this position (creates zero fill).
 #Include a digit (no fill).
 .Include decimal placeholder.
 %Convert number to percentage and include % sign.
 ,Include a thousands separator.
 E,-E+, e-,e+Convert to scientific notation.
 −, +, $, ( )Include these literal characters (no double quotes or \ is required to include these characters in numeric strings).
Date/Time:Include time separator.
 /Include date separator.
 cSame as General Date.
 d, ddInclude day of month as digit.
 dddInclude day of week as an abbreviation.
 ddddInclude full day of week.
 dddddSame as Short Date.
 ddddddSame as Long Date.
 aaaaInclude localized name of the weekday.
 wInclude day of week as a number (1 to 7).
 wwInclude week or year as number.
 m, mmInclude month as number. (Exception: includes minutes if it follows the hour, e.g., hh:mm.)
 mmmInclude month as an abbreviation.
 mmmmInclude full month name.
 ooooInclude full, localized month name.
 qInclude quarter of year (1 to 4).
 yInclude day of year (1 to 366).
 yy, yyyyInclude year as digit.
 h, hhInclude hour.
 n, nnInclude minute (or you can use m, mm if following hour).
 s, ssInclude second.
 tttttSame as Long Time.
 AM/PM, am/pm, A/P, a/pUse 12-hour time and include the specified meridian designator.
 AMPM, ampmUse 12-hour time and include the system meridian designator.

Some of the format codes in Tables 4 and 5 refer to system or localized settings. Those codes allow you to use the calendar and time features from the user's system, rather than using the default Visual Basic settings, which are based on the Julian calendar and English month and weekday names. It's important to be aware of those settings if your program is for use outside of the English-speaking world.

You can combine formatting code to produce quite sophisticated results. For example:

    Debug.Print Format(Now, """Today is ""dddd, mmmm d, yyyy" & _
""" the ""y""th day of the year. The time is now"" ttttt.")

displays this result:

    Today is Thursday, June 17, 2004 the 169th day of the year. The time is now
10:28:22 AM.



3. Change Strings

A lot of programming tasks involve getting or changing parts of a string. For simple replacement tasks, use the Replace method as shown here:

    Sub DemoSearchAndReplace( )
Dim str As String
str = "this is some text and some more text"
str = Replace(str, "some", "different")
Debug.Print str
End Sub

The preceding code replaces all instances of some with different in a case-sensitive way. Replace also provides option for replacing a certain number of occurrences, starting at a specific position within the string and doing case-insensitive searches. Replace also replaces one string with another regardless of their length. If the strings are the same length, you could use the Mid statement to change the source string, instead:

    Mid(str, InStr(1, str, "text")) = "word"
Debug.Print str
' Displays: this is different word and different more text

The Mid statement is unusual in that it receives an assignment—in this case the replacement string "word". Since Mid can't make strings longer or shorter, it is mainly useful for modifying string data that is in a fixed-width format or for replacing single characters, such as punctuation.

Visual Basic also provides a set of functions to remove leading, trailing, or leading and trailing whitespace characters from a string: LTrim, RTrim, and Trim. Excel does Visual Basic one better by adding the Trim worksheet function, which removes repeated internal spaces as well. The following code demonstrates each of the different trim functions:

    Sub DemoTrims( )
Dim str As String
str = " this is a string to trim. "
Debug.Print "LTrim:", ">"; LTrim(str); "<"
Debug.Print "RTrim:", ">"; RTrim(str); "<"
Debug.Print "Trim:", ">"; Trim(str); "<"
Debug.Print "Excel Trim:", ">"; _
WorksheetFunction.Trim(str); "<"
End Sub

The preceding code produces the following output in the Immediate window:

    LTrim:        >this is     a string   to trim.          <
RTrim: > this is a string to trim.<
Trim: >this is a string to trim.<
Excel Trim: >this is a string to trim.<

4. Repeat Characters

Finally, Visual Basic includes a couple of simple functions that create strings of repeated characters . The Space function returns a string containing spaces, and the String function returns a string containing a repeated character. Those functions are sometimes used in combination with Chr when creating reports or drawing text borders as shown here:

    ' Draws a little box in the Immediate window.
Sub DrawBox( )
Debug.Print Chr(1) & String(20, Chr(6)) & Chr(2)
Debug.Print Chr(5) & Space(20) & Chr(5)
Debug.Print Chr(5) & Space(20) & Chr(5)
Debug.Print Chr(5) & Space(20) & Chr(5)
Debug.Print Chr(3) & String(20, Chr(6)) & Chr(4)
End Sub
Other -----------------
- A Technical Overview of the Mobile Web : THE TECHNICAL CHALLENGES OF MOBILE DEVICES (part 2)
- A Technical Overview of the Mobile Web : THE TECHNICAL CHALLENGES OF MOBILE DEVICES (part 1) - Physical Constraints
- Parallel Programming with Microsoft Visual Studio 2010 : Task Parallelism - Unhandled Exceptions in Tasks
- Parallel Programming with Microsoft Visual Studio 2010 : Introduction to Parallel Tasks
- jQuery 1.3 : DOM Manipulation - Moving elements
- .NET Debugging : Introduction to the Tools - .NET 2.0—Redistributable & .NET 2.0—SDK
- .NET Debugging : Managed Heap and Garbage Collection
- Context and Interception : Custom Component Services (part 3) - The Transaction Management Service
- Context and Interception : Custom Component Services (part 2) - The Logbook Service
- Context and Interception : Custom Component Services (part 1) - Building a Custom Context Attribute & Installing a Custom Message Sink
- Software Testing with Visual Studio Team System 2008 : Data-driven unit testing
- Software Testing with Visual Studio Team System 2008 : Unit testing an ASP.NET application
- Microsoft Enterprise Library : Error Management Made Exceptionally Easy - Replacing an Exception & Logging an Exception
- Microsoft Enterprise Library : Error Management Made Exceptionally Easy - Diving in with a Simple Example
- iPhone Programming : Connecting to the Network - Embedding a Web Browser in Your App
- iPhone Programming : Connecting to the Network - Detecting Network Status
- Parallel Programming with Microsoft Visual Studio 2010 : Introduction to Parallel Programming - Software Patterns
- Parallel Programming with Microsoft Visual Studio 2010 : Introduction to Parallel Programming - Multicore Computing & Speedup
- Microsoft ASP.NET 3.5 : Web Services for ASP.NET AJAX Applications (part 2) - Consuming AJAX Web Services
- Microsoft ASP.NET 3.5 : Web Services for ASP.NET AJAX Applications (part 1) - Remote Calls via Web Services
 
 
 
Top 10
 
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 2) - Wireframes,Legends
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 1) - Swimlanes
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Formatting and sizing lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Adding shapes to lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Sizing containers
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 3) - The Other Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 2) - The Data Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 1) - The Format Properties of a Control
- Microsoft Access 2010 : Form Properties and Why Should You Use Them - Working with the Properties Window
- Microsoft Visio 2013 : Using the Organization Chart Wizard with new data
- First look: Apple Watch

- 3 Tips for Maintaining Your Cell Phone Battery (part 1)

- 3 Tips for Maintaining Your Cell Phone Battery (part 2)
programming4us programming4us